package com.tom.architect02.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;

/**
 * Added by Tom on 2024/03/08.
 */
public class PathSum {

    public static void main(String[] args) {
        PathSum solution = new PathSum();
        TreeNode root = new TreeNode(1);
        TreeNode right = new TreeNode(2);
        root.right = right;

        TreeNode rightLeft = new TreeNode(3);
        right.left = rightLeft;

        List<Integer>  res = solution.inorderTraversal(root);
        System.out.println(res); // [1, 3, 2]
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        Stack<TraversalOperate> operates = new Stack<>();
//        Queue<TraversalOperate> operates = new ArrayDeque<>(); // 栈
//        List<TraversalOperate> operates = new ArrayList<>();
        List<Integer> res = new ArrayList<>();
        operates.add(0, new TraversalOperate(1, root)); // gen

        while (!operates.isEmpty()) {
            TraversalOperate top = operates.pop();  // 拿第0个位置
            if (top.root == null) continue;

            if (top.operate == 0) { // 打印自己
                res.add(top.root.val); // 加入结果集
            } else {
                // 迭代写递归的思想
                operates.add(new TraversalOperate(1, top.root.right)); // 栈
                operates.add(new TraversalOperate(0, top.root)); // 打印自己节点
                operates.add(new TraversalOperate(1, top.root.left));
            }
        }
        return res;
    }


    public List<Integer> inorderTraversal2(TreeNode root) {
        Queue<TraversalOperate> operates = new ArrayDeque<>(); // 栈
        List<Integer> res = new ArrayList<>();
        operates.add(new TraversalOperate(1, root)); // gen

        while (!operates.isEmpty()) {
            TraversalOperate top = operates.remove();  // 拿第0个位置
            if (top.root == null) continue;

            if (top.operate == 0) { // 打印自己
                res.add(top.root.val); // 加入结果集
            } else {
                // 迭代写递归的思想。 栈：先进后出。
                operates.add(new TraversalOperate(1, top.root.left));
                operates.add(new TraversalOperate(0, top.root)); // 打印自己节点
                operates.add(new TraversalOperate(1, top.root.right)); // 栈
            }
        }
        return res;
    }

    class TraversalOperate {
        int operate; //0 打印，1 访问
        TreeNode root;

        public TraversalOperate(int operate, TreeNode root) {
            this.operate = operate;
            this.root = root;
        }
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
